package com.cyzy.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.mapper.EmailMapper;
import com.cyzy.mapper.EmailTemplateMapper;
import com.cyzy.pojo.EmailRecords;
import com.cyzy.pojo.EmailTemplates;
import com.cyzy.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;

@Service
public class EmailServiceImpl extends ServiceImpl<EmailMapper, EmailRecords> implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private EmailTemplateMapper templateMapper;

    @Autowired
    private EmailMapper emailMapper;

    @Value("${spring.mail.username}")
    private String sent;





    @Override
    public void emailLogin(String to,  Integer templateId, String userName, String code) {
        EmailTemplates byId = templateMapper.selectById(templateId);
        String text = byId.getContent();
        String subject = byId.getSubject();
//        int code = random.nextInt(MAX_RANDOM - MIN_RANDOM + 1) + MIN_RANDOM;
        text = text.replace("{verification_code}", code);
        text = text.replace("{user_name}", userName);
        System.out.println(text);
        sendSimpleEmail(to, subject, text, templateId);
    }




    public void sendSimpleEmail(String to, String subject, String text, Integer templateId) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sent);  //发件人
        message.setTo(to);  //收件人邮箱地址
        message.setSubject(subject);  //邮件主题
        message.setText(text); //HTML 格式的邮件内容

        EmailRecords emailRecords = new EmailRecords();
        emailRecords.setRecipientEmail(to);
        emailRecords.setSendTime(LocalDateTime.now());
        emailRecords.setContent(text);
        emailRecords.setSubject(subject);
        emailRecords.setTemplateId(templateId);
        emailRecords.setStatus("0");
        emailRecords.setSenderEmail(sent);

        emailMapper.insert(emailRecords);


        mailSender.send(message);
    }


}
